<template>
  <div class="icon-select">
    <div class="icon-select-header">
      <el-input
        v-model="filterName"
        placeholder="请输入图标名称"
        clearable
        @clear="filterIcons"
        @input="filterIcons"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <div class="icon-select-list">
      <div
        v-for="item in filteredIconList"
        :key="item"
        @click="selectedIcon(item)"
        class="icon-item"
        :title="item"
      >
        <svg-icon :icon-class="item" class-name="icon" />
        <span>{{ item }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import SvgIcon from '@/components/SvgIcon/index.vue'

// 图标列表
const iconList = ref([])
const filterName = ref('')

// 获取所有图标
const getIconList = () => {
  const modules = import.meta.glob('../../assets/icons/svg/*.svg')
  
  for (const path in modules) {
    const p = path.split('assets/icons/svg/')[1].split('.svg')[0]
    iconList.value.push(p)
  }
}

// 根据名称筛选图标
const filteredIconList = computed(() => {
  const name = filterName.value.toLowerCase()
  if (name) {
    return iconList.value.filter(item => item.toLowerCase().includes(name))
  }
  return iconList.value
})

// 图标过滤
const filterIcons = () => {
  filterName.value = filterName.value.trim()
}

// 选择图标
const emit = defineEmits(['selected'])
const selectedIcon = (name) => {
  emit('selected', name)
}

// 重置
const reset = () => {
  filterName.value = ''
}

// 暴露方法
defineExpose({
  reset
})

onMounted(() => {
  getIconList()
})
</script>

<style lang="scss" scoped>
.icon-select {
  width: 100%;
  
  .icon-select-header {
    padding: 10px;
  }
  
  .icon-select-list {
    height: 300px;
    overflow-y: auto;
    padding: 0 10px;
    display: flex;
    flex-wrap: wrap;
    
    .icon-item {
      width: 110px;
      height: 90px;
      margin: 5px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border: 1px solid #eee;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
        color: #409eff;
      }
      
      .icon {
        font-size: 24px;
        margin-bottom: 10px;
      }
      
      span {
        font-size: 12px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        width: 100%;
        text-align: center;
      }
    }
  }
}
</style> 